package v1

import (
	"context"
	"encoding/json"
	"fmt"

	"wxpay/internal/conf"
	"wxpay/internal/dto"
	"wxpay/internal/service"
	wxpay "wxpay/pkg/api/v1"

	mchApi "wxpay/pkg/wechat_api"
)

// 回调类通知 post /api/v1/wxpay/notify
func (s *Server) WxNotify(ctx context.Context, req *wxpay.NotifyRequest) (*wxpay.NotifyResponse, error) {
	fmt.Printf("/api/v1/wxpay/notify in => %+v", req)
	r := mchApi.CipherBlockResource{
		Algorithm:      req.Resource.Algorithm,
		Ciphertext:     req.Resource.Ciphertext,
		AssociatedData: req.Resource.AssociatedData,
		Nonce:          req.Resource.Nonce,
	}
	mchID := conf.Conf.Biz.MchIDAsService
	s.d.Logger.Info(ctx, fmt.Sprintf("/api/v1/wxpay/notify => %s", mchID))
	client, err := service.NewMchService(s.d).BuildMchApiClient(ctx, mchID)
	if err != nil {
		return nil, err
	}
	pText, err := client.GetResourcePlainText(r)
	if err != nil {
		return nil, err
	}
	// 根据pText 构建对应的业务通知对象DTO
	switch req.EventType {
	// 支付成功
	case string(mchApi.EVENTTYPE_TRANSACTION_SUCCESS):
		notification := dto.PayNotificationDTO{}
		err := json.Unmarshal(pText, &notification)
		if err != nil {
			return nil, err
		}
		if err = service.NewTransService(s.d).NotifyPayment(ctx, notification); err != nil {
			return nil, err
		}
		s.d.Logger.Info(ctx, fmt.Sprintf("/api/v1/wxpay/notify trade success => OutTradeNo(%s)", notification.OutTradeNo))
	//	退款通知
	case string(mchApi.EVENTTYPE_REFUND_SUCCESS), string(mchApi.EVENTTYPE_REFUND_CLOSED), string(mchApi.EVENTTYPE_REFUND_ABNORMAL):
		notification := dto.RefundNotificationDTO{}
		err := json.Unmarshal(pText, &notification)
		if err != nil {
			return nil, err
		}
		if err = service.NewRefundService(s.d).RefundNotify(ctx, &notification); err != nil {
			return nil, err
		}
		s.d.Logger.Info(ctx, fmt.Sprintf("/api/v1/wxpay/notify refund success => OutRefundNo(%s)", notification.OutRefundNo))
	}

	return &wxpay.NotifyResponse{Code: "SUCCESS"}, nil
}
